//
//  WaitForInterviewViewController.m
//  CYWFrame
//
//  Created by 于顺燊 on 2018/9/26.
//  Copyright © 2018年 Macx. All rights reserved.
//

#import "WaitForInterviewViewController.h"
#import "WaitForInterviewTableViewCell.h"
#import "InterviewChatViewController.h"
#import <WMPlayer.h>
#import <Masonry.h>

@interface WaitForInterviewViewController ()<UITableViewDelegate, UITableViewDataSource, WaitForInterviewTableViewCellDelegate, WMPlayerDelegate>

@property (strong, nonatomic) NSMutableArray *interviewInfoArr;
@property (strong, nonatomic) UITableView *tableView;

@end

@implementation WaitForInterviewViewController

- (void)viewWillAppear:(BOOL)animated
{
	NSInteger role = [GetUserDefaule(USERINFO)[@"role"] integerValue];
	if (role == 2 || role == 4) {
		[self getJobInfo];
	}
	else if(role == 5 || role == 6){
		[self getResumeInfo];
	}
}

- (void)viewDidLoad {
	[super viewDidLoad];
	
	// Do any additional setup after loading the view.
	[self createUI];
	[self refreshData];
}

- (void)createUI {
	
	if (self.mode == 1) {
		self.navigationItem.title = @"视频回放";
	}
	self.view.backgroundColor = UISeparatedColorRGB;
	_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-10) style:UITableViewStylePlain];
	_tableView.delegate = self;
	_tableView.dataSource = self;
	[_tableView registerNib:[UINib nibWithNibName:@"WaitForInterviewTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
	_tableView.backgroundColor = UISeparatedColorRGB;
	_tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
	[self.view addSubview:_tableView];
	
}

- (void)refreshData {
	__weak typeof (self) weakSelf = self;
	
	_tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
		NSLog(@"下拉刷新");
		NSInteger role = [GetUserDefaule(USERINFO)[@"role"] integerValue];
		if (role == 2 || role == 4) {
			[weakSelf getJobInfo];
		}
		else if(role == 5 || role == 6){
			[weakSelf getResumeInfo];
		}
	}];
}

//TableView delegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	WaitForInterviewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
	NSInteger role = [GetUserDefaule(USERINFO)[@"role"] integerValue];
	if (role == 2 || role == 4) {
		cell.type = 0;
		cell.model = self.interviewInfoArr[indexPath.row];
	}
	else if(role == 5 || role == 6){
		cell.type = 1;
		cell.model = self.interviewInfoArr[indexPath.row];
	}
	cell.delegate = self;
	cell.mode = self.mode;
	if (self.mode) {
		[cell.joinRoomBtn addActionWithblock:^{
			WMPlayerModel *playerModel = [WMPlayerModel new];
			playerModel.title = @"面试视频回放";
			NSString *url = [NSString stringWithFormat:@"http://livework.oss-cn-shenzhen.aliyuncs.com/%@",cell.model.video_url];
			playerModel.videoURL = [NSURL URLWithString:url];
			WMPlayer * wmPlayer = [[WMPlayer alloc]initPlayerModel:playerModel];
			wmPlayer.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT/1-64);
			[self.view addSubview:wmPlayer];
			wmPlayer.delegate = self;
			
			/*
			[wmPlayer mas_makeConstraints:^(MASConstraintMaker *make) {
				make.leading.trailing.top.equalTo(self.view);
				make.height.mas_equalTo(wmPlayer.mas_width).multipliedBy(9.0/16);
			}];
			 */
			[wmPlayer play];
		}];
	}
	cell.selectionStyle = UITableViewCellSelectionStyleNone;
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return self.interviewInfoArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return 130;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return 130;
}

- (void)getJobInfo
{
	NSDictionary *param;
	if (self.mode == 0) {
		param = @{@"status":@"0"};
	}
	else {
		param = @{@"status":@"4"};
	}
	[[NetworkTool sharedTool] requestWithName:@"获取个人面试管理信息(待面试)" URLString:APIPersonInterviewManage parameters:param method:@"POST" callBack:^(id responseObject) {
		
		[self.interviewInfoArr removeAllObjects];
		NSArray *arr = responseObject[@"data"];
		for (NSDictionary *dict in arr){
			InterviewManageModel *model = [[InterviewManageModel alloc] init];
			[model setValuesForKeysWithDictionary:dict];
			[self.interviewInfoArr addObject:model];
		}
		dispatch_async(dispatch_get_main_queue(), ^{
			[MBProgressHUD hideHUDForView:self.view animated:YES];
			[self.tableView.mj_header endRefreshing];
			[self.tableView reloadData];
		});
	}];
}

- (void)getResumeInfo
{
	NSDictionary *param;
	if (self.mode == 0) {
		param = @{@"status":@"0"};
	}
	else {
		param = @{@"status":@"4"};
	}
	[[NetworkTool sharedTool] requestWithName:@"获取企业面试管理信息(待面试)" URLString:APICompanyInterviewManage parameters:param method:@"POST" callBack:^(id responseObject) {
		
		[self.interviewInfoArr removeAllObjects];
		NSArray *arr = responseObject[@"data"];
		for (NSDictionary *dict in arr){
			InterviewManageModel *model = [[InterviewManageModel alloc] init];
			[model setValuesForKeysWithDictionary:dict];
			[self.interviewInfoArr addObject:model];
		}
		dispatch_async(dispatch_get_main_queue(), ^{
			[MBProgressHUD hideHUDForView:self.view animated:YES];
			[self.tableView.mj_header endRefreshing];
			[self.tableView reloadData];
		});
	}];
}

- (NSMutableArray *)interviewInfoArr
{
	if (!_interviewInfoArr) {
		_interviewInfoArr = [[NSMutableArray alloc] init];
	}
	return _interviewInfoArr;
}

- (void)joinRoom:(NSString *)roomId time:(NSString *)time interviewId:(NSString *)interviewId resumeId:(NSString *)resumeId positionId:(NSString *)positionId
{
	NSTimeInterval interviewTime = [time doubleValue];
	NSTimeInterval nowTime = [[NSDate date] timeIntervalSince1970];
	if (nowTime < interviewTime) {
		[self presentViewController:[LZCTools alertMessage:@"还没到面试时间"] animated:YES completion:nil];
		return;
	}
	else
	{
		UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定进入房间？" message:nil preferredStyle:UIAlertControllerStyleAlert];
		[alert addAction:[UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
		}]];
		[alert addAction:[UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
			
			NSInteger role = [GetUserDefaule(USERINFO)[@"role"] integerValue];
			if (role == 5 || role == 6) {
				[[NetworkTool sharedTool] requestWithName:@"面试开始" URLString:APIStartInterview parameters:@{@"interview_id":interviewId} method:@"POST" callBack:^(id responseObject) {
					//由于后台要调用声网的录制视频接口，返回需要很久，因而移动端直接往下走进入房间;
				}];
			}
			
			UIStoryboard *agoraSB = [UIStoryboard storyboardWithName:@"AgoraLive" bundle:nil];
			InterviewChatViewController *vc = (InterviewChatViewController *)[agoraSB instantiateViewControllerWithIdentifier:@"AgoraInterviewRoomVC"];
			vc.chatRoomId = roomId;
			vc.interviewId = interviewId;
			vc.resumeId = resumeId;
			vc.positionId = positionId;
			UIViewController *topRootViewController = [[UIApplication  sharedApplication] keyWindow].rootViewController;
			
			// 在这里加一个这个样式的循环
			while (topRootViewController.presentedViewController)
			{
				// 这里固定写法
				topRootViewController = topRootViewController.presentedViewController;
			}
			// 然后再进行present操作
			[topRootViewController presentViewController:vc animated:YES completion:nil];
			
		}]];
		[self presentViewController:alert animated:YES completion:nil];
	}
}


- (void)wmplayer:(WMPlayer *)wmplayer clickedCloseButton:(UIButton *)backBtn
{
	[wmplayer pause];
	[wmplayer removeFromSuperview];
	wmplayer = nil;
}

- (void)wmplayer:(WMPlayer *)wmplayer clickedFullScreenButton:(UIButton *)fullScreenBtn
{
	
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
